<?php
class Pageley_Commerce_Domain_Order extends Pageley_Domain_BasicEntity {
	public function __construct() {
		parent::__construct(self::type());
		$this->set("status", Pageley_Commerce_Domain_OrderStatus::$UNPLACED);
	}

	public static function type() {
		$factory = Pageley_Config::getInstance();
		return $factory->valueOf("type.commerce.Order");
	}

	public function add($orderItem) {
		if($orderItem === null || $orderItem->get("article") === null || !$orderItem->get("article")->get("active")) {
            throw new Pageley_Domain_Exception(
                new Pageley_I18n_Message("error.commerce.invalidArticleAdded"));
        }
        $status = $this->get("status");
		$status->tryAdd();
		$added = false;
		foreach($this->get("orderItems") as $oi) {
			if($oi->get("article")->equals($orderItem->get("article"))) {
				$quantity = $oi->get("quantity") + $orderItem->get("quantity");
				$oi->set("quantity", $quantity);
				$added = true;
				break;
			}
		}
		if(!$added) {
		    $this->get("orderItems")->add($orderItem);
		}
		$orderItem->set("order", $this);
	}

	public function remove($orderItem) {
		if($orderItem === null || !$this->get("orderItems")->containsValue($orderItem)) {
            throw new Pageley_Domain_Exception(
                new Pageley_I18n_Message("error.commerce.invalidArticleRemoved"));
        }
        $status = $this->get("status");
		$status->tryRemove();
		$this->get("orderItems")->removeValue($orderItem);
	}

	public function place() {
		$status = $this->get("status");
		$status->tryPlace();
		$this->set("status", Pageley_Commerce_Domain_OrderStatus::$PLACED);
		$this->set("datePlaced", new Pageley_Util_Timestamp());
	}

	public function cancel() {
		$status = $this->get("status");
		$status->tryCancel();
		$this->set("status", Pageley_Commerce_Domain_OrderStatus::$CANCELLED);
	}
	
	public function getTotalQuantity() {
	    $quantity = 0;
	    foreach($this->get("orderItems") as $orderItem) {
	        $quantity += $orderItem->get("quantity");
	    }
	    return $quantity;
	}
	
	public function getTotalAmount() {
	    $amount = 0;
        foreach($this->get("orderItems") as $orderItem) {
            $amount += $orderItem->get("quantity") * $orderItem->get("price")->get("value");
        }
        return $amount;
	}
	
	public function getCurrency() {
	    $orderItems = $this->get("orderItems");
	    $currency = null;
	    if($orderItems !== null && !$orderItems->isEmpty()) {
	        $currency = $orderItems->get(0)->get("price")->get("currency");
	    }
	    return $currency;
	}
}